home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Cream of the Crop 22
/
Cream of the Crop 22.iso
/
os2
/
edm0407s.zip
/
SEMSRC.ZIP
/
EXAMPLE.CPP
next >
Wrap
C/C++ Source or Header
|
1996-06-26
|
2KB
|
100 lines
/*
This has been compiled under Watcom C++ 10.5
It should compile with little or no modifications with other
compilers, but it has not been tested.
wcl386 -bm example.cpp
*/
#include <process.h> // for _beginthread
#include <iostream.h>
#include <string.h>
#include <string.hpp>
typedef String string; // fake the upcoming standard string library
#include "sync.h"
const STACKSIZE=1024*8;
struct Blob
{
Blob(Event* e, Mutex* m): event(e), mutex(m) {}
void Calc()
{
char* str="Important message";
for (int i=0; i< strlen(str); i++)
cout<<str[i];
cout<<endl;
}
Event* event;
Mutex* mutex;
};
void workerThread(void* arg);
/*
This program demonstrates the necessity of syncronising
threads. The shared resource in this example is the screen.
Without syncronisation, the output of the multiple threads
is intermixed, creating unreadable output.
To see the program use syncronisation, run the program without
any arguments. To see the chaos that results without any
syncronisation, run the program with one argument.
*/
int main(int argc, char* [])
{
Event done;
Mutex m,*pm;
ULONG nDone=0,tmpDone=0;
const MAXTASKS=10;
if (argc!=1)
pm=NULL;
else
pm=&m;
Blob blob(&done,pm);
for (int i=0; i<MAXTASKS; i++)
{
_beginthread(workerThread, NULL, STACKSIZE, &blob);
// use _beginthread to start a thread if it is going to utilise
// any c or C++ library routines. Other compilers may have
// slightly different function parameters.
}
while (nDone!=MAXTASKS)
{
done.Wait();
tmpDone=0;
done.Reset(&tmpDone);
nDone=nDone+tmpDone;
// This loop uses an event semaphore to wait until
// all the threads are done.
}
return 1;
}
void workerThread(void* arg)
{
Blob* pb=(Blob*)arg;
if (pb->mutex)
{
MutexLock lock(pb->mutex);
for (int i=0; i<2; i++)
pb->Calc();
}
else
{
for (int i=0; i<2; i++)
pb->Calc();
}
pb->event->Post();
}